<template>
  <el-dialog
    class="public-dialog"
    :title="disabled ? '黑名单详情' : `${isEdit ? '修改' : '新增'}黑名单`"
    width="674"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
    :close-on-click-modal="false"
  >
    <div class="h-[460px]">
      <XForm ref="form" :formData="model" :fieldList="fieldList" :options="formOption" :originOption="originOption" :rules="rules" v-if="!disabled">
        <template #a4-slot>
          <div class="text-[12px] text-[#9DA1AD] mt-[-10px]">收件人姓名/邮箱/收件电话，完全匹配到其中一项就满足拦截条件</div>
        </template>
        <template #a7-slot>
          <div class="text-[13px] text-[#9DA1AD]">订单的详细地址相似程度达到80%以上就会被拦截</div>
        </template>
      </XForm>

      <div v-else>
        <LookDtl :info="model" />
      </div>
    </div>
    <template #footer>
      <el-button :disabled="loading" @click="handleClose(false)">
        {{ disabled ? "关闭" : "取消" }}
      </el-button>
      <el-button v-if="!disabled" type="primary" :loading="loading" @click="handleSave"> 保存 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus"
import XForm from "@/components/XForm/index.vue"
import LookDtl from "./lookDtl.vue"
import { detailBlacklist, createBlackList, updateBlacklist } from "../../api/index"

const props = defineProps({
  id: { type: [String, Number], default: "" },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  originOption: { type: Object, default: () => ({}) },
})

const emit = defineEmits(["update:modelValue", "refresh", "close"])
const formOption = { inline: true, labelPosition: "top" }
const rules = {
  platform_id: [{ required: true, message: "请选择限制平台", trigger: "blur" }],
  reason: [{ required: true, message: "请输入拉黑理由", trigger: "blur" }],
  recipient_email: [{ type: "email", message: "请输入正确邮箱", trigger: ["blur", "change"] }],
}

const form = ref()
const loading = ref()
const model = ref({})
const fieldList = ref([
  {
    field: "platform_id",
    label: "限制平台",
    type: "select",
    tooltip: "通用表示：适用全部平台",
    style: { width: "280px" },
    originField: "platform",
  },
  { label: "黑名单匹配条件1", type: "title" },
  {
    field: "recipient_name",
    label: "收件人姓名",
    placeholder: "收件人姓名",
    style: { width: "120px" },
  },
  { field: "recipient_email", label: "邮箱", style: { width: "240px" } },
  { field: "recipient_phone", label: "收件电话", tooltip: "自动过滤空格和特殊符号，仅匹配数字", style: { width: "240px" } },
  { slot: "a4-slot" },
  { label: "黑名单匹配条件2", type: "title" },
  {
    field: "recipient_country",
    label: "收件国家",
    type: "select",
    originField: "country",
    style: { width: "248px" },
  },
  { field: "recipient_door_num", label: "门牌号", tooltip: "亚马逊平台可不用填写门牌号", style: { width: "120px" } },
  { field: "recipient_zip_code", label: "邮编", style: { width: "220px", marginRight: "-16px" } },
  { field: "recipient_province", label: "州/省", style: { width: "220px" } },
  { field: "recipient_city", label: "市/区", style: { width: "220px" } },
  {
    field: "recipient_address",
    label: "详细地址",
    type: "textarea",
    autosize: { minRows: 2, maxRows: 6 },
    style: { width: "620px" },
  },
  { label: "其他", type: "title" },
  { field: "order_sn", label: "来源订单", style: { width: "620px" } },
  { field: "reason", label: "拉黑理由", type: "textarea", autosize: { minRows: 2, maxRows: 6 }, style: { width: "620px" } },
])

watch(
  () => props.id,
  (val) => {
    if (val) {
      nextTick(() => {
        getDetail(val)
      })
    }
  }
)

const getDetail = async (id) => {
  try {
    const { data } = await detailBlacklist({ id })
    const { originOption } = props
    model.value = { ...data }
    model.value.platform = originOption["platform"].find((n) => data?.platform_id === n.value)?.label
  } catch (e) {
    model.value = {}
    console.error(e)
  }
}

const isEdit = computed(() => {
  return !!props.id
})

const handleSave = async () => {
  try {
    const formInfo = await form.value.submit()
    const api = {
      edit: updateBlacklist,
      add: createBlackList,
    }
    const { id, originOption } = props

    let platform = originOption["platform"].find((n) => formInfo?.platform_id == n.value)?.label || ""
    let recipient_country_name = originOption["country"].find((n) => formInfo?.recipient_country == n.value)?.label || ""
    await api[isEdit.value ? "edit" : "add"]({
      id: id || undefined,
      ...formInfo,
      platform,
      recipient_country_name,
    })
    ElMessage.success(isEdit.value ? "修改成功" : "保存成功")
    handleClose(true)
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息")
    }
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = async (refresh) => {
  model.value = {}
  await nextTick()
  form?.value?.resetForm()
  emit("update:modelValue", false)
  emit("close")
  if (refresh) emit("refresh")
}
</script>
<style lang="scss" scoped>
:deep(.el-form-item__label) {
  color: #333;
}
:deep(.form-components) {
  .el-form-item {
    margin-right: 16px;
  }
}
</style>
